/**
 * Created by ChenYong on 2017-07-12.
 *
 * 添加资源。
 */

$(function () {
    /** 资源表单的 jQuery 对象 */
    var $resourceForm = $("#resource_form");
    /** 父资源 ID 的 jQuery 对象 */
    var $parentId = $resourceForm.find("input[name='parentId']");
    /** 提交按钮的 jQuery 对象 */
    var $submitBtn = $resourceForm.find("button[name='submitBtn']");
    /** 权限代码远程正在校验的图标的 jQuery 对象 */
    var $checkIconLoading = $("#check_icon_loading");
    /** 权限代码远程校验通过的图标的 jQuery 对象 */
    var $checkIconSuccess = $("#check_icon_success");
    /** 权限代码远程校验未通过的图标的 jQuery 对象 */
    var $checkIconError = $("#check_icon_error");
    /** 显示校验信息的容器 */
    var $validateContainer = $("#validate_container");
    /** zTree 的 jQuery 对象 */
    var $zTree = $("#zTree");
    /** zTree id */
    var zTreeId = $zTree.attr("id");
    /** zTree 配置 */
    var zTreeSetting = {
        data: {
            simpleData: {
                idKey: "id",
                enable: true,
                pIdKey: "parentId",
                rootPId: 0
            }
        },
        view: {
            selectedMulti: false
        },
        check: {
            enable: true,
            chkStyle: "radio",
            radioType: "all"
        },
        callback: {
            onCheck: function (event, treeId, treeNode) {
                findCheckedParentId();
            }
        }
    };

    showZTree();

    $.validator.addMethod("checkResourceName", function (value, element) {
        return this.optional(element) || chineseRE.test(value);
    });

    $.validator.addMethod("checkResourceIcon", function (value, element) {
        return this.optional(element) || iconfontRE.test(value);
    });

    $.validator.addMethod("checkResourceUrl", function (value, element) {
        return this.optional(element) || urlOnlyRE.test(value);
    });

    $.validator.addMethod("checkPermissionCode", function (value, element) {
        return this.optional(element) || permissionRE.test(value);
    });

    $resourceForm.validate({
        ignore: [],
        rules: {
            resourceName: {
                required: true,
                maxlength: 50,
                checkResourceName: true
            },
            resourceIcon: {
                maxlength: 50,
                checkResourceIcon: true
            },
            resourceUrl: {
                maxlength: 500,
                checkResourceUrl: true
            },
            resourceType: {
                required: true,
            },
            permissionCode: {
                required: true,
                maxlength: 50,
                checkPermissionCode: true,
                remote: {
                    url: "{0}web/resource/check/permission_code.json".format(globalBasePath),
                    beforeSend: function () {
                        $checkIconLoading.removeClass("hide");
                        $checkIconSuccess.addClass("hide");
                        $checkIconError.addClass("hide")
                    },
                    dataFilter: function (data, type) {
                        $checkIconLoading.addClass("hide");

                        data = $.parseJSON(data);

                        // 传给服务器的资源代码未存在
                        if (data.resultCode == 0) {
                            $checkIconSuccess.removeClass("hide");

                            return true;
                        }

                        $checkIconError.removeClass("hide");

                        // 传给服务器的资源代码已存在
                        return false;
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        $checkIconLoading.addClass("hide");
                        $checkIconError.removeClass("hide");

                        // 获取状态码
                        var statusCode = xhr.status;
                        // 服务器返回的字符串
                        var responseText = xhr.responseText;

                        // 登录超时
                        if (statusCode == 401) {
                            $.toast({
                                top: 5,
                                msg: "您已登录超时，请重新登录",
                                type: "error",
                                close: 6000
                            });

                            // 无访问权限
                        } else if (statusCode == 403) {
                            $.toast({
                                top: 5,
                                msg: "您无访问权限，请联系管理授权",
                                type: "error",
                                close: 6000
                            });

                            // 请求参数不合法
                        } else if (statusCode == 412) {
                            $.toast({
                                top: 5,
                                msg: "您的请求参数不合法--->" + responseText,
                                type: "error",
                                close: 6000
                            });

                            // 访问的页面不存在
                        } else if (statusCode == 404) {
                            $.toast({
                                top: 5,
                                msg: "您访问的页面不存在",
                                type: "error",
                                close: 6000
                            });

                            // 服务器内部错误
                        } else if (statusCode == 500) {
                            $.toast({
                                top: 5,
                                msg: "系统繁忙，请稍候再试",
                                type: "error",
                                close: 6000
                            });

                            // 其他
                        } else {
                            $.toast({
                                top: 5,
                                msg: "网络连接失败，请稍候再试",
                                type: "error",
                                close: 6000
                            });
                        }
                    }
                }
            },
            parentId: {
                required: true,
            }
        },
        messages: {
            resourceName: {
                required: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>请输入资源名称</span>",
                maxlength: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>资源名称的长度不能大于{0}个字符</span>",
                checkResourceName: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>资源名称由汉字、数字（0-9）、字母（a-z, A-Z）、下划线（_）、斜杠（/）组成</span>"
            },
            resourceIcon: {
                maxlength: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>资源图标的长度不能大于{0}个字</span>",
                checkResourceIcon: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>资源图标的格式不正确，如：<i class='iconfont icon-bell f-s-12'></i>（iconfont icon-bell）</span>"
            },
            resourceUrl: {
                maxlength: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>资源URL的长度不能大于{0}个字</span>",
                checkResourceUrl: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>资源URL的格式不正确，如：/web/index.html"
            },
            resourceType: {
                required: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>请选择资源类型</span>"
            },
            permissionCode: {
                required: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>请输入权限代码</span>",
                maxlength: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>权限代码的长度不能大于{0}个字符</span>",
                checkPermissionCode: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>权限代码由(0-9)、(a-z)、(_)、(:)、(*)组成，且以(a-z)开头，如：user:* 或 user:create</span>",
                remote: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>权限代码已存在，请重新输入</span>"
            },
            parentId: {
                required: "<span class='f-s-12'><i class='iconfont icon-error f-s-12'></i>请选择父资源</span>"
            }
        },
        errorContainer: $validateContainer,
        errorLabelContainer: $("ul", $validateContainer),
        wrapper: "li",
        submitHandler: function (form) {
            $submitBtn.html("<i class='ace-icon fa fa-spinner fa-spin bigger-150'></i>正在提交…").attr({"disabled": "disabled"});

            return true;
        }
    });

    /**
     * 显示 ZTree。
     */
    function showZTree() {
        $.myAjax({
            url: "web/resource/ztree.json",
            data: {
                id: 0
            },
            modal: true,
            successFn: function (data) {
                // 初始化 zTree
                $.fn.zTree.init($zTree, zTreeSetting, data.results);
            }
        });
    }

    /**
     * 查找被选中的父资源 ID。
     */
    function findCheckedParentId() {
        // 获取 zTree 对象
        var zTreeObj = $.fn.zTree.getZTreeObj(zTreeId);
        // 获取所有 node
        var nodes = zTreeObj.transformToArray(zTreeObj.getNodes());
        // 父资源 ID
        var parentId = "";

        // 查找被选中的节点
        $.each(nodes, function (i, e) {
            if (e.checked) {
                parentId = e.id;

                // 终止循环
                return false;
            }
        });

        if ($.isBlank(parentId)) {
            $parentId.val("");
        } else {
            $parentId.val(parentId);
        }
    }
});